<?php

namespace app\model;

use think\Model;
use app\model\Welfare;

class Collect extends Model
{
    protected $autoWriteTimestamp = true;

    /**
     * 收藏任务
     *
     * @param [type] $user_id
     * @param [type] $task_id
     * @return void
     */
    public static function collectTask($user_id, $task_id)
    {
        if (self::where('user_id', $user_id)->where('task_id', $task_id)->find()) {
            self::where('user_id', $user_id)->where('task_id', $task_id)->delete();
            return '取消收藏';
        } else {
            self::create(['user_id' => $user_id, 'task_id' => $task_id]);
            return '已收藏';
        }
    }

    /**
     * 收藏列表
     *
     * @param [type] $user_id
     * @return void
     */
    public static function getList($user_id)
    {
        $page = input('page');
        if (empty($page)) {
            $page = 1;
        }
        $limit = input('limit');
        if (empty($limit)) {
            $limit = 10;
        }
        $page_count = ($page - 1) * $limit;

        $list['data'] = self::alias('c')
            ->join('task t', 'c.task_id = t.id')
            ->where('c.user_id', $user_id)
            ->where('t.is_show', 0)
            ->where('t.delete_time', null)
            ->field('t.id, t.work_name, t.company_name, t.welfare, t.pay_min, t.pay_max, t.recruit_num, t.address_sheng, t.address_shi, t.address_details, t.create_time')
            ->limit($page_count, $limit)
            ->order('c.create_time desc')
            ->select();
        foreach($list['data'] as $k => $v) {
            if (!empty($v['welfare'])) {
                $welfare_id = is_array($v['welfare']) ? $v['welfare']: json_decode($v['welfare'], true);
                $list['data'][$k]['welfare_name'] = Welfare::whereIn('id', $welfare_id)->column('welfare_name');
            }
        }
        $list['count'] = self::alias('c')
            ->join('task t', 'c.task_id = t.id')
            ->where('c.user_id', $user_id)
            ->where('t.is_show', 0)
            ->where('t.delete_time', null)
            ->count();
        $list['page'] = $page;
        
        return $list;
    }
}